﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Form
{
    public partial class ICM_Purchase_Request : System.Web.UI.Page
    {
        IBLLTree bllTree = new TreeBLL();
        IBLLSysYearType bllYearType = new SysYearTypeBLL();
        IBLLMasterPurchaseType bllPurchaseType = new MasterPurchaseTypeBLL();
        IBLLSysRecordStatus bllStatus = new SysRecordStatusBLL();
        IBLLSysProgress bllProgress = new SysProgressBLL();
        IBLLPrePurchaseRequest bllPPR = new PrePurchaseRequestBLL();
        IBLLMasterPurchaseMethod bllMasPurchaseMethod = new MasterPurchaseMethodBLL();
        PurchaseRequestBLL bllPurchaseRequest = new PurchaseRequestBLL();
        IBLLHrmEmployee bllEmployee = new HrmEmployeeBLL();
        SysControlBLL bllSysCon = new SysControlBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDefault();
                LoadYearType();
                LoadJobSiteTree();
                LoadPurchaseType();
                LoadRecordStatus();
                LoadJobSiteTree();
                LoadPurchaseMethod();
                LoadOperationName();
                LoadDataGrid();
                //LoadDataGridUrgent();
            }
        }

        protected void LoadDefault()
        {
            SysControlInfo infoDefault = bllSysCon.GetDefaultData();
            if (infoDefault.YearType != null)
            {
                cbYearType.SelectedValue = infoDefault.YearType.ToString();
                Session["YearType"] = Convert.ToInt32(cbYearType.SelectedValue.ToString());
            }
            if (infoDefault.Year != null)
            {
                txtYear.Text = infoDefault.Year.ToString();
                Session["Year"] = Convert.ToInt32(txtYear.Text);
            }
        }

        protected void LoadDataGrid()
        {
            int YearType = Convert.ToInt32(cbYearType.SelectedValue.ToString());
            int Year = Convert.ToInt32(txtYear.Text);
            RadTreeView tree = (RadTreeView)cbJobSite.Items[0].FindControl("TreeViewJobSite");
            Nullable<int> JobSiteSeq = (tree.SelectedValue.ToString() != "") ? (Nullable<int>)Convert.ToInt32(tree.SelectedValue.ToString()) : null;
            Nullable<int> PurchaseTypeSeq = (cbPurchaseType.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbPurchaseType.SelectedValue.ToString()) : null;
            Nullable<int> PurchaseMethodSeq = (cbPurchaseMethod.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbPurchaseMethod.SelectedValue.ToString()) : null;
            string OperationName = (cbOperationName.SelectedValue.ToString() != "") ? cbOperationName.SelectedValue.ToString() : "";
            string RecordStatus = (cbStatus.SelectedValue.ToString() != "") ? cbStatus.SelectedValue.ToString() : "";

            IList<PurchaseRequestInfo> infoPurchaseRequest = bllPurchaseRequest.GetPurchaseRequest(YearType, Year, JobSiteSeq, PurchaseTypeSeq, PurchaseMethodSeq, OperationName, RecordStatus,1);
            Grid.DataSource = infoPurchaseRequest;
            GridGroupByExpression g;
            Grid.MasterTableView.GroupByExpressions.Clear();
            g = new GridGroupByExpression(Grid.Columns[1]);
            Grid.MasterTableView.GroupByExpressions.Add(g);
            Grid.DataBind();
        }

        protected void LoadYearType()
        {
            IList<SysYearTypeInfo> infoList = bllYearType.GetSysYearType();
            cbYearType.DataSource = infoList;
            cbYearType.DataBind();
        }

        protected void LoadPurchaseType()
        {
            IList<MasterPurchaseTypeInfo> infoList = bllPurchaseType.GetMasterPurchaseType();
            cbPurchaseType.DataSource = infoList;
            cbPurchaseType.DataBind();
            //cbPurchaseType1.DataSource = infoList;
            //cbPurchaseType1.DataBind();
        }

        protected void LoadRecordStatus()
        {
            IList<SysRecordStatusInfo> infoList = bllStatus.GetSysRecordStatusTransaction();
            cbStatus.DataSource = infoList;
            cbStatus.DataBind();
        }

        protected void LoadJobSiteTree()
        {
            IList<TreeInfo> info = bllTree.GetJobSiteTree();
            RadTreeView tree = (RadTreeView)cbJobSite.Items[0].FindControl("TreeViewJobSite");

            tree.DataSource = info;
            tree.DataBind();
        }

        protected void LoadPurchaseMethod()
        {
            IList<MasterPurchaseMethodInfo> infoList = bllMasPurchaseMethod.GetNameListMasterPurchaseMethod();
            cbPurchaseMethod.DataSource = infoList;
            cbPurchaseMethod.DataBind();
        }

        protected void LoadOperationName()
        {
            IList<HrmEmployeeInfo> infoEmp = bllPPR.GetPrePurchaseRequestOperationName(1);
            cbOperationName.DataSource = infoEmp;
            cbOperationName.DataBind();
        }

        protected void btnShow_Click(object sender, EventArgs e)
        {
            Session["YearType"] = Convert.ToInt32(cbYearType.SelectedValue.ToString());
            Session["Year"] = Convert.ToInt32(txtYear.Text);

            if (RadTabStrip1.SelectedTab.Value == "Normal")
            {
                LoadDataGrid();
            }
            else
            {
                LoadDataGridUrgent();
            }
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            IList<PurchaseRequestInfo> infoList = new List<PurchaseRequestInfo>();
            foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
            {
                PurchaseRequestInfo info = new PurchaseRequestInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPurchaseRequest.DeleteAll(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }
            LoadDataGrid();
        }

        protected void RadManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
        {
            if (e.Argument == "CloseWindow")
            {
                LoadDataGrid();
            }
            else
            {
                LoadDataGridUrgent();
            }
        }

        protected void Grid_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            LoadDataGrid();
        }

        protected void cbNewOperationName_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmEmployeeInfo> infoList = bllEmployee.GetHrmEmployee(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                RadComboBox cbAppEmp = (RadComboBox)sender;
                cbAppEmp.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].InfoJobSite.Name;
                tdJobSite.Width = Unit.Pixel(200);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(150);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                TableCell tdPosition = new TableCell();
                Label lblPosition = new Label();
                lblPosition.Text = infoList[i].InfoPosition.Name;
                tdPosition.Width = Unit.Pixel(150);
                tdPosition.Controls.Add(lblPosition);
                tr.Cells.Add(tdPosition);
                TableCell tdClass = new TableCell();
                Label lblClass = new Label();
                lblClass.Text = infoList[i].InfoClass.Name;
                tdClass.Width = Unit.Pixel(190);
                tdClass.Controls.Add(lblClass);
                tr.Cells.Add(tdClass);
                ((Table)cbAppEmp.Items[j].FindControl("tableNewOperationName")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        protected void cbNewOperationName_Urgent_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmEmployeeInfo> infoList = bllEmployee.GetHrmEmployee(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                RadComboBox cbAppEmp = (RadComboBox)sender;
                cbAppEmp.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].InfoJobSite.Name;
                tdJobSite.Width = Unit.Pixel(200);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(150);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                TableCell tdPosition = new TableCell();
                Label lblPosition = new Label();
                lblPosition.Text = infoList[i].InfoPosition.Name;
                tdPosition.Width = Unit.Pixel(150);
                tdPosition.Controls.Add(lblPosition);
                tr.Cells.Add(tdPosition);
                TableCell tdClass = new TableCell();
                Label lblClass = new Label();
                lblClass.Text = infoList[i].InfoClass.Name;
                tdClass.Width = Unit.Pixel(190);
                tdClass.Controls.Add(lblClass);
                tr.Cells.Add(tdClass);
                ((Table)cbAppEmp.Items[j].FindControl("tableNewOperationName_Urgent")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void btnSendTo_Click(object sender, EventArgs e)
        {
            IList<PurchaseRequestInfo> infoList = new List<PurchaseRequestInfo>();
            foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
            {
                PurchaseRequestInfo info = new PurchaseRequestInfo();
                RecordInfo infoRecord = new RecordInfo();
                HrmEmployeeInfo infoEmp = new HrmEmployeeInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                infoEmp.Seq = Convert.ToInt32(cbNewOperationName.SelectedValue.ToString());
                info.InfoRecord = infoRecord;
                info.InfoPurchaseEmp = infoEmp;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert("โปรดเลือกรายการที่ต้องการเปลี่ยนผู้ดำเนินการ");
                return;
            }

            try
            {
                bllPurchaseRequest.ChangePurchaseEmployee(infoList);
                LoadDataGrid();
                RadManager1.Alert("เปลี่ยนผู้ดำเนินการเรียบร้อยแล้ว");
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
        }

        protected void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            if (RadTabStrip1.SelectedTab.Value == "Normal")
            {
                LoadDataGrid();
            }
            else
            {
                LoadDataGridUrgent();
            }
        }

        protected void OnAjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            RadAjaxPanel1.Controls.Add(Page.LoadControl("../UserControl/Personal_Data.ascx"));
        }

        //-------------------------------------------------------------------------------------------------------------

        protected void LoadDataGridUrgent()
        {
            int YearType = Convert.ToInt32(cbYearType.SelectedValue.ToString());
            int Year = Convert.ToInt32(txtYear.Text);

            cbPurchaseType.SelectedIndex = -1;
            cbPurchaseType.Text = "";
            cbPurchaseMethod.SelectedIndex = -1;
            cbPurchaseMethod.Text = "";
            RadTreeView tree = (RadTreeView)cbJobSite.Items[0].FindControl("TreeViewJobSite");
            Nullable<int> JobSiteSeq = (tree.SelectedValue.ToString() != "") ? (Nullable<int>)Convert.ToInt32(tree.SelectedValue.ToString()) : null;
            Nullable<int> PurchaseTypeSeq = (cbPurchaseType.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbPurchaseType.SelectedValue.ToString()) : null;
            Nullable<int> PurchaseMethodSeq = (cbPurchaseMethod.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbPurchaseMethod.SelectedValue.ToString()) : null;
            string OperationName = (cbOperationName.SelectedValue.ToString() != "") ? cbOperationName.SelectedValue.ToString() : "";
            string RecordStatus = (cbStatus.SelectedValue.ToString() != "") ? cbStatus.SelectedValue.ToString() : "";

            IList<PurchaseRequestInfo> infoPurchaseRequest = bllPurchaseRequest.GetPurchaseRequest(YearType, Year, JobSiteSeq, PurchaseTypeSeq, PurchaseMethodSeq, OperationName, RecordStatus, 2);
            Grid_Urgent.DataSource = infoPurchaseRequest;
            GridGroupByExpression g;
            Grid_Urgent.MasterTableView.GroupByExpressions.Clear();
            g = new GridGroupByExpression(Grid_Urgent.Columns[1]);
            Grid_Urgent.MasterTableView.GroupByExpressions.Add(g);
            Grid_Urgent.DataBind();
        }

        protected void Grid_Urgent_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            LoadDataGridUrgent();
        }

        protected void btnSendTo_Urgent_Click(object sender, EventArgs e)
        {
            IList<PurchaseRequestInfo> infoList = new List<PurchaseRequestInfo>();
            foreach (GridDataItem data in Grid_Urgent.MasterTableView.GetSelectedItems())
            {
                PurchaseRequestInfo info = new PurchaseRequestInfo();
                RecordInfo infoRecord = new RecordInfo();
                HrmEmployeeInfo infoEmp = new HrmEmployeeInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                infoEmp.Seq = Convert.ToInt32(cbNewOperationName_Urgent.SelectedValue.ToString());
                info.InfoRecord = infoRecord;
                info.InfoPurchaseEmp = infoEmp;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert("โปรดเลือกรายการที่ต้องการเปลี่ยนผู้ดำเนินการ");
                return;
            }

            try
            {
                bllPurchaseRequest.ChangePurchaseEmployee(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
            LoadDataGridUrgent();
        }

        protected void Delete_Urgent_Click(object sender, EventArgs e)
        {
            IList<PurchaseRequestInfo> infoList = new List<PurchaseRequestInfo>();
            foreach (GridDataItem data in Grid_Urgent.MasterTableView.GetSelectedItems())
            {
                PurchaseRequestInfo info = new PurchaseRequestInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPurchaseRequest.DeleteAll(infoList);
                LoadDataGridUrgent();
                RadManager1.Alert("เปลี่ยนผู้ดำเนินการเรียบร้อยแล้ว");
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }
        }

        protected void clearFilter_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid.MasterTableView.FilterExpression = string.Empty;
            LoadDataGrid();
        }

        protected void clearFilter_Urgent_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid_Urgent.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid_Urgent.MasterTableView.FilterExpression = string.Empty;
            LoadDataGridUrgent();
        }
    }
}
